/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *  SRVStreamingFixedLengthBinaryResponseBuffer.m - iPhoneSRV console for Surveyor SRV-1 and SVS 
 *
 *  Created by Nick Kitchener.  Copyright (C) 2009  Surveyor Corporation 
 *            and Nick Kitchener.  All rights reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details (www.gnu.org/licenses)
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#import "SRVStreamingFixedLengthBinaryResponseBuffer.h"


@implementation SRVStreamingFixedLengthBinaryResponseBuffer

@synthesize isComplete;

-(id)init {
	if( self =[super init] ) {
		byteBuffer=NULL;
		streamingOffset=0;
		remainingToRead=0;
		isComplete=NO;
	}
	return self;
}

-(void) dealloc {
	if( byteBuffer != NULL ) {
		free(byteBuffer);
		byteBuffer = NULL;
	}
	[super dealloc];
}

-(void)setResponseLength:(NSUInteger)length {
	if( byteBuffer ) {
		// old buffer exists (obviously not read before!
		free(byteBuffer);
		byteBuffer = NULL;
	}
	byteBuffer = malloc( sizeof(uint8_t[length]) );
	streamingOffset = 0;
	remainingToRead = length;
	isComplete = NO;
}

-(void)insertInitalData:(uint8_t *)dataPtr length:(NSUInteger)length {
	if( byteBuffer ) {
		memcpy(byteBuffer, dataPtr, length);
		streamingOffset = length;
		remainingToRead -= length;
	}
}

-(void)haveBytes:(CFReadStreamRef)inputStream {
	if(!isComplete) {
		NSUInteger bytesRead = CFReadStreamRead(inputStream, &byteBuffer[streamingOffset], remainingToRead);
		remainingToRead-=bytesRead;
		streamingOffset+=bytesRead;
		if(remainingToRead==0)
			isComplete=YES;
	}
	
}
/*
-(void)haveBytes:(NSInputStream*)inputStream {
	if(!isComplete) {
		NSUInteger bytesRead = [inputStream read:&byteBuffer[streamingOffset] maxLength:remainingToRead];
		remainingToRead-=bytesRead;
		streamingOffset+=bytesRead;
		if(remainingToRead==0) {
			isComplete=YES;
		}
	}
}*/

// note - hands over ownership.
-(void)getResponse:(uint8_t **)returnPtr {
	*returnPtr=byteBuffer;
	byteBuffer = NULL;
}

@end
